<script setup>
import { ref, onMounted } from 'vue'
import { getDoctorOrders } from '../../api/doctor'
import { getUser } from '../../api/user'
// import { listPackageItems, listIndicators } from '../../api/admin' // removed
import { useAuthStore } from '../../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const auth = useAuthStore()
const list = ref([])
const total = ref(0)
const query = ref({ status: '', orderType: '', page: 1, size: 10 })
const loading = ref(false)
const userNameMap = ref({})

// 移除手动采样相关状态与表单（改为系统自动生成）
// const sampleDialog = ref(false)
// const sampleForm = ref({ orderId: null, sampleType: '', remark: '' })
// const itemsDialog = ref(false)
// const itemsOrderId = ref(null)
// const indicatorList = ref([])
// const selectedIndicatorIds = ref([])
// const sampleTypeForItems = ref('')
// const remarkForItems = ref('')

// 手动采样相关函数已移除（改为订单确认后自动生成样本）

// 医生确认订单（将状态置为 2：已确认，可填写备注）
const confirmOrder = async (row) => {
  if (row.status !== 1) return
  try {
    const { value } = await ElMessageBox.prompt('可填写确认备注（可留空）', '确认该订单？', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPlaceholder: '医生备注（可选）',
    })
    loading.value = true
    const commonApi = await import('../../api/common')
    await commonApi.updateOrderStatus(row.orderId, { status: 2, remark: value || undefined })
    ElMessage.success('订单已确认，系统已自动生成待采集样本')
    await fetchList()
  } catch (e) {
    // 用户取消或请求失败
  } finally {
    loading.value = false
  }
}

// 新增：完成订单（置为 3），默认要求订单已确认；可选校验样本已全部完成
const completeOrder = async (row) => {
  if (row.status !== 2) return
  loading.value = true
  try {
    const commonApi = await import('../../api/common')
    // 拉取该订单下样本，校验完成度
    const samplesRes = await commonApi.listSamples({ orderId: row.orderId, page: 1, size: 500 })
    const samples = samplesRes.list || []
    const totalCount = samples.length
    const doneCount = samples.filter(s => s.status === 4).length

    if (totalCount > 0 && doneCount < totalCount) {
      await ElMessageBox.confirm(`该订单共有 ${totalCount} 个样本，已完成 ${doneCount} 个。确认仍然将订单标记为“已完成”？`, '样本未全部完成', {
        type: 'warning',
        confirmButtonText: '仍然完成',
        cancelButtonText: '取消',
      })
    }

    const { value: remark } = await ElMessageBox.prompt('可填写完成备注（可留空）', '完成该订单？', {
      confirmButtonText: '完成',
      cancelButtonText: '取消',
      inputPlaceholder: '完成备注（可选）',
    })

    await commonApi.updateOrderStatus(row.orderId, { status: 3, remark: remark || undefined })
    ElMessage.success('订单已标记为完成')
    await fetchList()
  } catch (e) {
    // 用户取消或请求失败
  } finally {
    loading.value = false
  }
}

const fetchList = async () => {
  loading.value = true
  try {
    const data = await getDoctorOrders(auth.currentId, {
      status: query.value.status || undefined,
      orderType: query.value.orderType || undefined,
      page: query.value.page,
      size: query.value.size,
    })
    list.value = data.list || []
    total.value = data.total || 0
    // 加载用户姓名映射
    const ids = Array.from(new Set((list.value || []).map(it => it.userId).filter(Boolean)))
    if (ids.length) {
      try {
        const results = await Promise.all(ids.map(id => getUser(id).catch(() => null)))
        const map = {}
        results.forEach((u, idx) => { const id = ids[idx]; map[id] = (u && (u.name || u.username)) || '-' })
        userNameMap.value = map
      } catch (e) {
        // 忽略姓名加载失败，维持空映射
        userNameMap.value = {}
      }
    } else {
      userNameMap.value = {}
    }
  } finally {
    loading.value = false
  }
}

// 显示优化：状态与类型的中文映射与标签类型（数字状态）
const statusLabel = (s) => ({
  1: '待确认',
  2: '已确认',
  3: '已完成',
  4: '已取消',
}[s] || s)
const statusTagType = (s) => ({
  1: 'warning',
  2: 'info',
  3: 'success',
  4: 'danger',
}[s] || 'default')
const orderTypeLabel = (t) => ({
  PACKAGE: '套餐',
  INDICATOR: '项目',
}[t] || t)

onMounted(fetchList)
</script>

<template>
  <el-card>
    <h3>我的体检订单</h3>
    <el-form :inline="true" :model="query" class="mb-2">
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="全部" style="width:150px">
          <el-option label="全部" value="" />
          <el-option label="待确认" :value="1" />
          <el-option label="已确认" :value="2" />
          <el-option label="已完成" :value="3" />
          <el-option label="已取消" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="query.orderType" placeholder="全部" style="width:150px">
          <el-option label="全部" value="" />
          <el-option label="套餐" value="PACKAGE" />
          <el-option label="项目" value="INDICATOR" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query.page=1;fetchList()">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 提示：订单确认后自动生成样本，无需手动采集 -->
    <el-alert type="info" show-icon title="提示" class="mb-2"
      description="订单确认后，系统会根据指标的标本类型（如血液、尿液）自动生成待采集样本。您可在“样本采集管理”页面查看与更新状态。" />

    <el-table :data="list" v-loading="loading" style="width:100%">
      <el-table-column prop="orderId" label="订单ID" width="100" />
      <el-table-column label="用户" width="140">
        <template #default="{ row }">{{ userNameMap[row.userId] || '-' }}</template>
      </el-table-column>
      <el-table-column label="医生" width="140">
        <template #default>{{ auth.user?.name || '-' }}</template>
      </el-table-column>
      <el-table-column prop="orderType" label="类型" width="120">
        <template #default="{ row }">{{ orderTypeLabel(row.orderType) }}</template>
      </el-table-column>
      <el-table-column prop="orderDate" label="体检日期" width="140" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.status)" size="small">{{ statusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="success" size="small" :disabled="row.status !== 1" @click="confirmOrder(row)">确认订单</el-button>
          <el-button type="primary" size="small" class="ml-1" :disabled="row.status !== 2" @click="completeOrder(row)">完成订单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-2">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="query.size"
        :current-page="query.page"
        @current-change="(p)=>{query.page=p;fetchList()}"
      />
    </div>
  </el-card>

  <!-- 移除：批量采集与单个采样对话框（改为自动生成） -->
  <!-- （此处不再保留任何采样弹窗） -->
</template>

<style scoped>
.mb-2{ margin-bottom:12px; }
.mt-2{ margin-top:12px; }
</style>